package thread;

import org.junit.Test;
import util.ThreadUtil;

import java.util.concurrent.Semaphore;

/**
 * @author wuguojian
 * @description
 * @date 2022/7/27 下午3:11
 **/
public class SemaphoreTest {

    @Test
    public void test(){
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0 ; i < 10 ; i++){
            new Thread(() -> {
                try {
                    ThreadUtil.print("尝试进入停车场...");
                    //尝试获取许可
                    semaphore.acquire();
                    //模拟停车
                    long time = (long) (Math.random() * 10 + 1);
                    ThreadUtil.print("进入了停车场，停车" + time + "秒...");
                    ThreadUtil.sleep(time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    ThreadUtil.print("开始驶离停车场...");
                    //释放许可
                    semaphore.release();
                    ThreadUtil.print("离开了停车场！");
                }
            }, i + "号汽车").start();
        }
        ThreadUtil.sleep(10000);
    }

}
